/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */ 

package com.nokia.example.wordpress.views;

import com.nokia.example.wordpress.components.DataModel;
import com.nokia.example.wordpress.helpers.ImageLoader;
import com.nokia.example.wordpress.networking.Blog;
import com.nokia.example.wordpress.networking.GetCommentsOperation;
import com.nokia.example.wordpress.networking.GetRecentPostsOperation;
import com.nokia.example.wordpress.networking.GetUsersBlogsOperation;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

/**
 * View to display a logo and some loading information.
 */
public class LoaderView extends BaseView {

    private Image loaderScreen;
    private String message = "";
    
    LoaderView(Graphics g, int x, int y, int width, int height) {
        super(g, ViewMaster.VIEW_LOADER, x, y, width, height);
        try {
            loaderScreen = ImageLoader.getInstance().loadImage("/loader_screen.png");
        } catch (IOException e) {
        }
    }
  
    public void activate()
    {
        System.out.println("loader activate");
        super.activate();
        startupSequence();
    }

    public void draw(int x, int y, int width, int height) {
        System.out.println("loader render");
        viewMaster.drawBackground(g, x, y, width, height, false);
        drawLogoScreen(message);
    }

    public void drawLogoScreen(String text) {
        // Check whether the wide lower part of the graphic fits into the
        // screen width. If not, clip it out.
        int gfxHeight = loaderScreen.getHeight();
        if (width <= 270) {
            // Only draw this much from the top of the graphic.
            gfxHeight = 165;
        }
        g.drawRegion(loaderScreen, 0, 0, loaderScreen.getWidth(), gfxHeight,
                Sprite.TRANS_NONE, width / 2, 0, g.TOP | g.HCENTER);
        g.setColor(Visual.BACKGROUND_COLOR);
        final int textY = height - Visual.SMALL_FONT.getHeight() - 8;
        g.fillRect(0, textY, width, Visual.SMALL_FONT.getHeight());
        g.setColor(Visual.LOGO_TEXT_COLOR);
        g.setFont(Visual.SMALL_FONT);
        g.drawString(text, width / 2, height - 8, g.BOTTOM | g.HCENTER);
    }

    private void setProgressMessage(String message)
    {
        this.message = message;
        viewMaster.draw();
    }

     /**
     * Loads the blog, blog posts and comments.
     */
    private void startupSequence() {
        
        // Clear error message.
        data.setLoginMessage("");

        // Construct local listeners for networking operations:

        final GetCommentsOperation.Listener commentsListener = new GetCommentsOperation.Listener() {

            // After receiving comments, store them and enter the posts view.
            public void commentsReceived(Vector comments) {
                System.out.println("commentsReceived " + comments.size());
                data.setComments(comments);
                viewMaster.setView(ViewMaster.VIEW_POSTS);
            }
        };

        final GetRecentPostsOperation.Listener postsListener = new GetRecentPostsOperation.Listener() {

            // After receiving posts, store them and get comments.
            public void postsReceived(Vector posts) {
                System.out.println("postsReceived " + posts.size());
                setProgressMessage("Loading comments");
                data.setPosts(posts);
                GetCommentsOperation op = new GetCommentsOperation(commentsListener, data.getBlog(), data.getPosts());
                op.start();
            }
        };


        final GetUsersBlogsOperation.Listener blogsListener = new GetUsersBlogsOperation.Listener() {

            //  After getting (or trying to get) the blogs, some error case can be checked.
            public void blogsReceived(Vector blogs) {
                if (blogs == null || blogs.size() == 0) {
                    data.setLoginMessage("Login error!");
                    viewMaster.setView(ViewMaster.VIEW_LOGIN);
                } else {
                    // Grab the first blog for loading the posts from.
                    // Other blogs are ignored in this application.
                    Blog blog = (Blog) blogs.elementAt(0);
                    data.setBlog(blog);
                    if (data.getBlog().faultString != null) {
                        // Server responed with a readable error message, display it.
                        data.setLoginMessage(blog.faultString);
                      viewMaster.setView(ViewMaster.VIEW_LOGIN);
                    } else {
                        // No errors, save the cretentials and get posts.
                        data.saveLoginCredentials();
                        data.setLoginMessage("");
                        setProgressMessage("Loading posts");
                        GetRecentPostsOperation op = new GetRecentPostsOperation(postsListener, data.getBlog());
                        op.start();
                    }

                }
            }
        };

        // The first step, load blogs.
        setProgressMessage("Loading blogs");
        GetUsersBlogsOperation op = new GetUsersBlogsOperation(blogsListener, data.getBlogUrl(),
                data.getLoginUsername(), data.getLoginPassword());
        op.start();

    }


}
